package cn.xiaopengstack.domain.trade.rule.refund;

import cn.xiaopengstack.domain.trade.model.aggregate.GroupBuyOrderRefundAggregate;
import cn.xiaopengstack.domain.trade.model.entity.*;
import cn.xiaopengstack.domain.trade.model.valobj.RefundTypeEnumVO;
import cn.xiaopengstack.domain.trade.repository.ITradeRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

/**
 * 未支付退单
 * @author jiangyangang
 */
@Service
@Slf4j
public class UnpaidToUnlockStrategy extends AbstractRefundStrategy{
    public UnpaidToUnlockStrategy(ITradeRepository tradeRepository) {
        super(tradeRepository);
    }

    @Override
    public TradeRefundResponseEntity apply(TradeRefundCommandAggregate tradeRefundCommandAggregate) throws Exception{
        TradeRefundRequestEntity tradeRefundRequestEntity = tradeRefundCommandAggregate.getTradeRefundRequestEntity();
        GroupBuyOrderListEntity groupBuyOrderListEntity = tradeRefundCommandAggregate.getGroupBuyOrderListEntity();
        // 查询订单
        String refundOrderId = RandomStringUtils.randomNumeric(12);
        tradeRepository.unlockOrder(GroupBuyOrderRefundAggregate
                .builder()
                .groupBuyOrderListEntity(groupBuyOrderListEntity)
                .userEntity(UserEntity.builder()
                        .userId(tradeRefundRequestEntity.getUserId())
                        .build())
                .tradeRefundRequestEntity(tradeRefundRequestEntity)
                .refundOrderId(refundOrderId)
                .build());

        return TradeRefundResponseEntity.builder()
                .teamId(groupBuyOrderListEntity.getTeamId())
                .tradeRefundResponseStatusEnum(TradeRefundResponseEntity.TradeRefundResponseStatusEnum.SUCCESS)
                .userId(groupBuyOrderListEntity.getUserId())
                .refundOrderId(refundOrderId)
                .build();
    }

    @Override
    public RefundTypeEnumVO type() {
        return RefundTypeEnumVO.unpay_unlock;
    }
}
